package com.taskmanager.service;

import com.taskmanager.dao.TaskDao;
import com.taskmanager.dto.TaskListResponse;
import com.taskmanager.dto.TaskRequest;
import com.taskmanager.dto.TaskResponse;
import com.taskmanager.entity.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 任务业务逻辑层
 */
@Service
public class TaskService {
    
    @Autowired
    private TaskDao taskDao;
    
    /**
     * 创建任务
     * @param userId 用户ID
     * @param request 任务请求
     * @return 任务响应
     */
    @Transactional(rollbackFor = Exception.class)
    public TaskResponse createTask(Long userId, TaskRequest request) {
        // 验证数据
        if (request.getTitle() == null || request.getTitle().trim().isEmpty()) {
            throw new IllegalArgumentException("任务标题不能为空");
        }
        
        // 创建任务对象
        Task task = new Task();
        task.setUserId(userId);
        task.setCategoryId(request.getCategoryId());
        task.setTitle(request.getTitle());
        task.setDescription(request.getDescription());
        task.setPriority(request.getPriority() != null ? request.getPriority() : "MEDIUM");
        task.setStatus(request.getStatus() != null ? request.getStatus() : "TODO");
        task.setDueDate(request.getDueDate());
        
        // 保存到数据库
        int result = taskDao.insert(task);
        if (result <= 0) {
            throw new RuntimeException("创建任务失败");
        }
        
        // 查询完整信息（包含分类）
        Task created = taskDao.selectByIdWithCategory(task.getTaskId());
        
        return convertToResponse(created);
    }
    
    /**
     * 查询任务列表（支持筛选、排序）
     * @param userId 用户ID
     * @param keyword 搜索关键词
     * @param status 状态
     * @param priority 优先级
     * @param categoryId 分类ID
     * @param sortBy 排序字段
     * @param sortOrder 排序方向
     * @return 任务列表响应
     */
    public TaskListResponse getTaskList(Long userId, String keyword, String status, 
                                       String priority, Long categoryId, 
                                       String sortBy, String sortOrder) {
        // 查询任务列表
        List<Task> tasks = taskDao.selectByConditions(
            userId, keyword, status, priority, categoryId, sortBy, sortOrder
        );
        
        // 转换为响应DTO
        List<TaskResponse> taskResponses = tasks.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        
        // 查询统计信息
        Map<String, Object> rawStatistics = taskDao.countByStatus(userId);
        
        // 转换统计数据类型，处理BigDecimal到Integer的转换
        Map<String, Integer> statistics = new java.util.HashMap<>();
        if (rawStatistics != null) {
            for (Map.Entry<String, Object> entry : rawStatistics.entrySet()) {
                Object value = entry.getValue();
                if (value instanceof Number) {
                    statistics.put(entry.getKey(), ((Number) value).intValue());
                } else {
                    statistics.put(entry.getKey(), 0);
                }
            }
        }
        
        return new TaskListResponse(taskResponses, statistics);
    }
    
    /**
     * 查询任务详情
     * @param taskId 任务ID
     * @param userId 用户ID
     * @return 任务响应
     */
    public TaskResponse getTaskById(Long taskId, Long userId) {
        // 验证任务所有权
        if (!taskDao.belongsToUser(taskId, userId)) {
            throw new IllegalArgumentException("无权访问此任务");
        }
        
        Task task = taskDao.selectByIdWithCategory(taskId);
        if (task == null) {
            throw new IllegalArgumentException("任务不存在");
        }
        
        return convertToResponse(task);
    }
    
    /**
     * 更新任务
     * @param taskId 任务ID
     * @param userId 用户ID
     * @param request 任务请求
     * @return 任务响应
     */
    @Transactional(rollbackFor = Exception.class)
    public TaskResponse updateTask(Long taskId, Long userId, TaskRequest request) {
        // 验证任务所有权
        if (!taskDao.belongsToUser(taskId, userId)) {
            throw new IllegalArgumentException("无权操作此任务");
        }
        
        // 更新任务
        Task task = new Task();
        task.setTaskId(taskId);
        task.setCategoryId(request.getCategoryId());
        task.setTitle(request.getTitle());
        task.setDescription(request.getDescription());
        task.setPriority(request.getPriority());
        task.setStatus(request.getStatus());
        task.setDueDate(request.getDueDate());
        
        int result = taskDao.update(task);
        if (result <= 0) {
            throw new RuntimeException("更新任务失败");
        }
        
        // 查询更新后的任务
        Task updated = taskDao.selectByIdWithCategory(taskId);
        
        return convertToResponse(updated);
    }
    
    /**
     * 删除任务
     * @param taskId 任务ID
     * @param userId 用户ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteTask(Long taskId, Long userId) {
        // 验证任务所有权
        if (!taskDao.belongsToUser(taskId, userId)) {
            throw new IllegalArgumentException("无权操作此任务");
        }
        
        int result = taskDao.deleteById(taskId);
        if (result <= 0) {
            throw new RuntimeException("删除任务失败");
        }
    }
    
    /**
     * 更新任务状态
     * @param taskId 任务ID
     * @param userId 用户ID
     * @param status 新状态
     * @return 任务响应
     */
    @Transactional(rollbackFor = Exception.class)
    public TaskResponse updateTaskStatus(Long taskId, Long userId, String status) {
        // 验证任务所有权
        if (!taskDao.belongsToUser(taskId, userId)) {
            throw new IllegalArgumentException("无权操作此任务");
        }
        
        // 验证状态值
        if (!status.equals("TODO") && !status.equals("IN_PROGRESS") && !status.equals("COMPLETED")) {
            throw new IllegalArgumentException("无效的状态值");
        }
        
        int result = taskDao.updateStatus(taskId, status);
        if (result <= 0) {
            throw new RuntimeException("更新状态失败");
        }
        
        // 查询更新后的任务
        Task updated = taskDao.selectByIdWithCategory(taskId);
        
        return convertToResponse(updated);
    }
    
    /**
     * 将任务从一个分类移动到另一个分类
     * @param fromCategoryId 源分类ID
     * @param toCategoryId 目标分类ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void moveTasksCategoryToOther(Long fromCategoryId, Long toCategoryId) {
        taskDao.updateCategoryBatch(fromCategoryId, toCategoryId);
    }
    
    /**
     * 查询即将到期的任务
     * @param userId 用户ID
     * @param days 天数
     * @return 任务列表
     */
    public List<TaskResponse> getUpcomingTasks(Long userId, int days) {
        List<Task> tasks = taskDao.selectUpcomingTasks(userId, days);
        
        return tasks.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 获取任务统计信息
     * @param userId 用户ID
     * @return 统计信息Map
     */
    public Map<String, Integer> getTaskStatistics(Long userId) {
        Map<String, Object> rawStatistics = taskDao.countByStatus(userId);
        
        // 转换统计数据类型，处理BigDecimal到Integer的转换
        Map<String, Integer> statistics = new java.util.HashMap<>();
        if (rawStatistics != null) {
            for (Map.Entry<String, Object> entry : rawStatistics.entrySet()) {
                Object value = entry.getValue();
                if (value instanceof Number) {
                    statistics.put(entry.getKey(), ((Number) value).intValue());
                } else {
                    statistics.put(entry.getKey(), 0);
                }
            }
        }
        
        return statistics;
    }
    
    /**
     * 判断任务是否即将到期
     * @param task 任务对象
     * @return 到期状态：today, tomorrow, overdue, normal
     */
    public String getDueDateStatus(Task task) {
        if (task.getDueDate() == null) {
            return "normal";
        }
        
        if (task.getStatus() != null && task.getStatus().equals("COMPLETED")) {
            return "normal";
        }
        
        java.time.LocalDate today = java.time.LocalDate.now();
        java.time.LocalDate dueDate = task.getDueDate();
        
        if (dueDate.isBefore(today)) {
            return "overdue";  // 已过期
        } else if (dueDate.isEqual(today)) {
            return "today";  // 今天到期
        } else if (dueDate.isEqual(today.plusDays(1))) {
            return "tomorrow";  // 明天到期
        } else {
            return "normal";
        }
    }
    
    /**
     * 将Task实体转换为TaskResponse
     */
    private TaskResponse convertToResponse(Task task) {
        TaskResponse response = new TaskResponse();
        response.setTaskId(task.getTaskId());
        response.setTitle(task.getTitle());
        response.setDescription(task.getDescription());
        response.setPriority(task.getPriority());
        response.setStatus(task.getStatus());
        response.setCategoryId(task.getCategoryId());
        response.setCategoryName(task.getCategoryName());
        response.setCategoryColor(task.getCategoryColor());
        response.setDueDate(task.getDueDate());
        response.setCreatedAt(task.getCreatedAt());
        response.setUpdatedAt(task.getUpdatedAt());
        return response;
    }
}
